﻿

using System;
using System.IO;
using LibGit2Sharp;
using LibGit2Sharp.Handlers;


namespace git
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {


            string sourceFile = @"D:\test.txt";        // D盘源文件
            string repoPath = @"C:\LocalGitRepo\study";      // 本地仓库路径
            string targetFileName = "test1.txt";        // 仓库中的文件名
            string commitMessage = "Initial commit with file from D drive";
            string gitlabUrl = "https://gitee.com/binyongliang/study.git"; // 替换为你的GitLab仓库URL
           // string gitlabUrl = "https://ccsmsgit.magna.global/dev/study.git";
          //  string branchName = "main";
            string branchName = "master";
            string username = "binyongliang";         // GitLab 用户名
            string pat = "BYL924902978";              // GitLab PAT

            //string username = "deanbin";         // GitLab 用户名
           // string pat = "WOSHIBIN-4321";              // GitLab PAT

            try
            {
                // ===== 1. 创建本地仓库目录 =====
                if (!Directory.Exists(repoPath))
                {
                    Directory.CreateDirectory(repoPath);
                    Console.WriteLine($"创建仓库目录: {repoPath}");
                }

                // ===== 2. 初始化本地Git仓库 =====
                if (!Repository.IsValid(repoPath))
                {
                    Repository.Init(repoPath);
                    Console.WriteLine("初始化新的Git仓库");
                }

                // ===== 3. 复制文件到仓库 =====
                string targetPath = Path.Combine(repoPath, targetFileName);
                File.Copy(sourceFile, targetPath, overwrite: true);
                Console.WriteLine($"已将文件复制到仓库: {targetPath}");

                // ===== 4. Git 操作 =====
                using (var repo = new Repository(repoPath))
                {
                    // 检查并创建主分支（如果需要）
                    if (repo.Head == null)
                    {
                        repo.CreateBranch(branchName);
                        Commands.Checkout(repo, repo.Branches[branchName]);
                        Console.WriteLine($"创建并切换到分支: {branchName}");
                    }

                    // 添加远程仓库
                    if (repo.Network.Remotes["origin"] == null)
                    {
                        repo.Network.Remotes.Add("origin", gitlabUrl);
                        Console.WriteLine("添加远程仓库: origin");
                    }






                    //添加暂存文件----add

                    // 暂存文件
                    Commands.Stage(repo, targetFileName);
                    Console.WriteLine("文件已暂存");

                    //提交文件到本地仓库----commit
                    // 检查是否有更改需要提交
                    var status = repo.RetrieveStatus();
                    if (status.IsDirty)
                    {
                        // 提交更改
                        var author = new Signature(username, $"{username}@magna.com", DateTimeOffset.Now);
                        repo.Commit(commitMessage, author, author);
                        Console.WriteLine("提交更改完成");
                    }
                    else
                    {
                        Console.WriteLine("没有需要提交的更改");
                    }

 





                    
                    // 推送到 GitLab----push
                    var remote = repo.Network.Remotes["origin"];
                    var pushOptions = new PushOptions
                    {
                        CredentialsProvider = (url, user, cred) =>
                            new UsernamePasswordCredentials { Username = username, Password = pat }
                    };

                    // 获取当前分支引用
                    var branch = repo.Head;

                    // 设置上游分支（首次推送需要）
                    repo.Branches.Update(branch,
                        b => b.Remote = remote.Name,
                        b => b.UpstreamBranch = branch.CanonicalName);

                    // 推送分支
                    repo.Network.Push(branch, pushOptions);
                    Console.WriteLine("✅ 文件成功推送到 GitLab！");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 错误: {ex.Message}");
                Console.WriteLine($"详细信息: {ex.InnerException?.Message}");
            }




        }




    }
}









